package com.nexgo.payment.action.scan;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.oaf.apiv3.device.scanner.OnScannerListener;
import com.nexgo.oaf.apiv3.device.scanner.Scanner;
import com.nexgo.oaf.apiv3.device.scanner.ScannerCfgEntity;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 扫码输入
 * <p>
 * Created by wanghongyang on 2017/9/1.
 */
public class ScanPresenter implements ScanContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(ScanPresenter.class.getSimpleName());

    private final ScanContract.View mView;
    private DataSource mRepository;
    private Scanner mScanner;
    private boolean isFirstTimes = true;

    public ScanPresenter(@NonNull ScanContract.View view, @NonNull DataSource dataSource) {
        this.mView = checkNotNull(view);
        this.mRepository = checkNotNull(dataSource);
        view.setPresenter(this);
        mScanner = ApiDeviceEngine.getInstance().getScanner(App.sContext);
    }

    @Override
    public void start() {
        if (isFirstTimes) {
            onStartScanner();
            isFirstTimes = false;
        }
    }

    @Override
    public void pause() {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void onStartScanner() {
        try {
            ScannerCfgEntity cfgEntity = new ScannerCfgEntity();
            cfgEntity.setAutoFocus(true);
            cfgEntity.setBulkMode(false);
            cfgEntity.setUsedFrontCcd(false);
            mScanner.initScanner(cfgEntity, mInitScannerListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStopScanner() {
        if (mScanner != null) {
            mScanner.stopScan();
        }
    }

    @Override
    public void onErrCode(int retCode) {
        switch (retCode) {
            case SdkResult.TimeOut:
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_time_out)));
                break;
            case SdkResult.Scanner_Customer_Exit:
                postMainThread(() -> mView.showErrMsg(null));
                break;
            default:
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_fail)));
                break;
        }
    }

    /**
     * 初始化扫码回调
     */
    private OnScannerListener mInitScannerListener = new OnScannerListener() {
        @Override
        public void onInitResult(int retCode) {
            mLog.debug("初始化扫码，返回状态：{}", retCode);
            if (retCode != SdkResult.Success) {
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_init_error)));
                return;
            }
            int result = mScanner.startScan(SysConstant.TIME_OUT_60, mStartScannerListener);
            mLog.debug("启动扫码，返回状态：{}", result);
            if (result != SdkResult.Success) {
                postMainThread(() -> mView.showErrMsg(App.sContext.getString(R.string.scan_start_error)));
            }
        }

        @Override
        public void onScannerResult(int retCode, String data) {
        }
    };

    /**
     * 扫码结果回调
     */
    private OnScannerListener mStartScannerListener = new OnScannerListener() {

        @Override
        public void onInitResult(int retCode) {
        }

        @Override
        public void onScannerResult(int retCode, String data) {
            mLog.debug("扫码结果，返回状态：{}", retCode);
            if (retCode != SdkResult.Success) {
                onErrCode(retCode);
                return;
            }
            mLog.debug("扫码返回数据：{}", data);
            postMainThread(() -> mView.showScanSuccessful(data));
        }
    };

    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        if (mView.isActive()) {
            runnable.run();
        }
    }
}
